﻿using Inovout.Data.Service;
using KuaJing.Organization.Domain;

namespace KuaJing.Organization.Service
{
    public class OrganizationService : RepositoryService<OrganizationUnit>
    {
        //private readonly string userid = "jiw";
        //private readonly string key = "uieHDj93Wx";
        //private readonly string domain = "samples.cn";
        //private readonly string account = "samples.cn";
        //IRepositoryService<Employee> employeeService;
        //IRepositoryService<Contact> contactService;
        //IRepositoryService<Position> positionService;
        //IRepositoryService<Person> personService;
        //IRepositoryService<OrganizationUnit> organizationUnitService;
        //IRepositoryService<MailCredential> mailCredentialService;
        //IRepositoryService<MembershipUser> membershipUserService;
        //public OrganizationService()
        //{
        //    employeeService = ComponentRegistry.Resolve<IRepositoryService<Employee>>();
        //    contactService = ComponentRegistry.Resolve<IRepositoryService<Contact>>();
        //    positionService = ComponentRegistry.Resolve<IRepositoryService<Position>>();
        //    organizationUnitService = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
        //    personService = ComponentRegistry.Resolve<IRepositoryService<Person>>();
        //    mailCredentialService = ComponentRegistry.Resolve<IRepositoryService<MailCredential>>();
        //    membershipUserService = ComponentRegistry.Resolve<IRepositoryService<MembershipUser>>();
        //}
        //public void Sync263()
        //{
        //    SyncOrganization("307");
        //    SyncEmployee();
        //}

        #region Organization
        //private void SyncOrganization(string rooId)
        //{
        //    //organizationUnitService.Save(GetRootOrganization(rooId));
        //    OrganizationUnit organizationUnit = GetRootOrganization(rooId);
        //    organizationUnitService.Save(organizationUnit);



        //}
        //private OrganizationUnit GetRootOrganization(string rootId)
        //{
        //    XmapiImplService service = new XmapiImplService();
        //    string sign = Md5Sign(userid + domain + account + key);
        //    string xml = service.getDepartment(userid, domain, account, sign);
        //    IEnumerable<XElement> organizationElements = XDocument.Parse(xml).Descendants("department");
        //    var rootOrganization = BuildOrganization(organizationElements.Single(e => e.Element("departmentId").Value == rootId));
        //    BuildChildOrganizations(rootOrganization, rootId, organizationElements);
        //    return rootOrganization;
        //}
        //private OrganizationUnit BuildOrganization(XElement element, string parentPath = null)
        //{
        //    string name = element.Element("departmentName").Value;
        //    string namePath = parentPath == null ? name : parentPath + "/" + name;
        //    return organizationUnitService.Query().SingleOrDefault(org => org.NamePath == namePath) ??
        //     new OrganizationUnit(name, namePath) { DepartmentId = element.Element("departmentId").Value };
        //}
        //private void BuildChildOrganizations(OrganizationUnit parent, string parentId, IEnumerable<XElement> organizationElements)
        //{
        //    foreach (var element in organizationElements.Where(e => e.Element("depId").Value == parentId))
        //    {
        //        OrganizationUnit child = BuildOrganization(element, parent.NamePath);
        //        child.Parent = parent;
        //        parent.Children.Add(child);
        //        BuildChildOrganizations(child, element.Value, organizationElements);
        //    }
        //}
        //private string Md5Sign(string str)
        //{
        //    MD5 md5 = new MD5CryptoServiceProvider();
        //    byte[] buffer = Encoding.Default.GetBytes(str);
        //    string result = BitConverter.ToString(md5.ComputeHash(buffer));
        //    return result.Replace("-", "").ToLower();
        //}
        #endregion

        #region Employee
        //private void SyncEmployee()
        //{
        //    XmapiImplService service = new XmapiImplService();
        //    string sign = Md5Sign(domain + account + key);
        //    string xml = service.getDomainUserlist_New(domain, account, sign);
        //    var userElements = XDocument.Parse(xml).Descendants("user");
        //    foreach (var organization in organizationUnitService.Query().ToArray())
        //    {
        //        //Q Org.Position通过迭代Employee。Position来提取。在Orgazization中实现，不在这里实现。
        //        BuildEmployees(organization, userElements);
        //        organizationUnitService.Save(organization);
        //    }
        //}
        //private void BuildEmployees(OrganizationUnit organization, IEnumerable<XElement> userElements)
        //{
        //    //Q 未来可以通过两个集合，一个为数据库，另一个为Xml，处理离职员工的信息。
        //    // foreach (XElement element in userElements.Where(u => u.Element("domainid").Value == organization.NamePath))
        //    foreach (XElement element in userElements.Where(u => u.Element("departmentid").Value == organization.DepartmentId))
        //    {
        //        var employee = BuildEmployee(element);
        //        if (!organization.Employees.Contains(employee))
        //        {
        //            organization.addEmployee(employee);
        //        }
        //    }
        //}
        //private Employee BuildEmployee(XElement element)
        //{
        //    string mail = element.Element("userid").Value;
        //    string name = element.Element("name").Value;
        //    string mobile = element.Element("mobile") == null ? null : element.Element("mobile").Value;
        //    string position = element.Element("office").Value;
        //    Contact mobileContact = string.IsNullOrEmpty(mobile) ? null :
        //        contactService.Query().SingleOrDefault(c => c.Label == ContactMethod.Mobile && c.Value == mobile) ?? new Contact(ContactMethod.Mobile, mobile);
        //    Contact mailContact = contactService.Query().SingleOrDefault(c => c.Label == ContactMethod.EMail && c.Value == mail) ?? new Contact(ContactMethod.EMail, mail);
        //    if (mailContact.Person != null && mailContact.Person == mobileContact.Person)
        //    {
        //        return employeeService.Query().Single(e => e.Person == mailContact.Person);
        //    }
        //    else
        //    {
        //        return new Employee(BuildPerson(name, mobileContact, mailContact), BuildPosition(position));
        //    }
        //}

        //private Person BuildPerson(string name, Contact mobileContact, Contact mailContact)
        //{
        //    Person person = new Person(name, mobileContact, mailContact);
        //    BuildMembershipUser(person);
        //    return person;
        //}

        //private Position BuildPosition(string position)
        //{
        //    return positionService.Query().SingleOrDefault(p => p.Name == position) ?? new Position(position);
        //}
        #endregion


        #region MembershipUser

        //private void BuildMembershipUser(Person person)
        //{
        //    var mail = person.Contacts.SingleOrDefault(e => e.Label == ContactMethod.EMail).Value;
        //    MailCredential mailCredential = mailCredentialService.Query()
        //          .SingleOrDefault(a => a.Mail == mail) ?? new MailCredential(mail);
        //    MembershipUser membershipUser = new MembershipUser();
        //    membershipUser.Credentials.Add(mailCredential);
        //    membershipUser.Name = mailCredential.Identity;
        //    PersonMembership membership = new PersonMembership(person);
        //    membershipUser.Membership = membership;
        //    membershipUserService.Save(membershipUser);
        //}

        #endregion
    }
}
